//
//  PPProfileViewController.m
//  pickpic
//
//  Created by GaoYongyue on 16/9/11.
//  Copyright © 2016年 MicroDream. All rights reserved.
//

#import "PPProfileViewController.h"
#import "PPFanUserListViewController.h"
#import "PPFollowingUserListViewController.h"
#import "PPCommentTimelineViewController.h"
#import "PPUserInfoViewController.h"
#import "PPTimelinePictureViewController.h"
#import "PPMessageTimelineViewController.h"

#import "PPProfileTableViewSectionHeaderView.h"

#import "PPProfileTableViewFlowCell.h"
#import "PPProfileTableViewCommentCell.h"

#import "PPProfileHeaderView.h"

#import "PPAlbumObject.h"

#import "PPAlbumShareView.h"
#import "PPAlbumShareActionView.h"

#import "PPSocializationManager.h"
#import "PPUnreadMessageManager.h"

static const NSInteger kCount = 30;
typedef NS_ENUM(NSUInteger, PPProfileViewAlbumLayoutType) {
    PPProfileViewAlbumLayoutTypeTimeline,
    PPProfileViewAlbumLayoutTypeFlow,
};

@interface PPProfileViewController () <PPProfileTableViewFlowCellDelegate, PPProfileTableViewSectionHeaderViewDelegate, PPCommentTimelineViewControllerDelegate>
@property (nonatomic, strong) PPProfileHeaderView *headerView;
@property (readwrite, nonatomic, assign) PPProfileViewAlbumLayoutType layoutType;
@end

@implementation PPProfileViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupBackItem];
    _layoutType = PPProfileViewAlbumLayoutTypeTimeline;

    self.tableView.backgroundColor = [UIColor colorWithRGBHex:0xf2f2f2];

    [self.tableView registerNib:[UINib nibWithNibName:@"PPProfileTableViewFlowCell" bundle:nil] forCellReuseIdentifier:@"flowCell"];
    [self.tableView registerClass:[PPProfileTableViewCommentCell class] forCellReuseIdentifier:@"commentCell"];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    _headerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([PPProfileHeaderView class]) owner:nil options:nil].firstObject;
    _headerView.frame = CGRectMake(0, 0, self.view.width, 171);
    _headerView.delegateViewController = self;

    __weak typeof(self)weakSelf = self;
    [_headerView.albumLabel setActionBlock:^(UIControl *control) {
        [MobClick event:@"82"];
        [weakSelf changeLayoutType];
    } forEvent:UIControlEventTouchUpInside];

    [self updateNavigationBar];

    [self reloadHeaderView];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveNicknameDidChangeNotification:) name:PPAccountProfilesNicknameDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveAvatarDidChangeNotification:) name:PPAccountProfilesAvatarDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveUnreadMessageSummaryDidChangeNotification) name:PPUnreadMessageSummaryDidChangeNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self fetchUserPublicInfoWithCallback:nil];
}

- (void)didReceiveUnreadMessageSummaryDidChangeNotification {
    [self updateNavigationBar];
}

- (void)didReceiveNicknameDidChangeNotification:(NSNotification *)notification {
    [self reloadHeaderView];

    NSString *nickname = notification.object;
    PPUserID userID = DGCurrentAccount.userID;

    for(PPAlbumObject *album in self.items) {
        if([album.userID isEqualToString:userID]) {
            album.ownerName = nickname;
        }

        for(PPTimelineCommentObject *comment in album.comments) {
            PPTimelineUserObject *sender = comment.sender;

            if([sender.userID isEqualToString:userID]) {
                sender.name = nickname;
            }

            PPTimelineUserObject *receiver = comment.receiver;

            if([receiver.userID isEqualToString:userID]) {
                receiver.name = nickname;
            }
        }
    }

    [self cacheItems:self.items];

    [self.tableView reloadData];
}

- (void)didReceiveAvatarDidChangeNotification:(NSNotification *)notification {
    [self reloadHeaderView];

    NSString *avatar = notification.object;
    NSString *avatarHost = [notification.userInfo validStringForKey:@"avatarHost"];
    NSString *avatarKey = [notification.userInfo validStringForKey:@"avatarKey"];
    PPUserID userID = DGCurrentAccount.userID;

    for(PPAlbumObject *album in self.items) {
        if([album.userID isEqualToString:userID]) {
            album.ownerAvatar = avatar;
        }

        for(PPTimelineCommentObject *comment in album.comments) {
            PPTimelineUserObject *sender = comment.sender;

            if([sender.userID isEqualToString:userID]) {
                sender.avatarKey = avatarKey;
                sender.avatarHost = avatarHost;
            }

            PPTimelineUserObject *receiver = comment.receiver;

            if([receiver.userID isEqualToString:userID]) {
                receiver.avatarKey = avatarKey;
                receiver.avatarHost = avatarHost;
            }
        }
    }

    [self cacheItems:self.items];

    [self.tableView reloadData];
}

- (void)reloadHeaderView {
    PPAccountProfiles *profiles = [PPAccountProfiles existingProfilesForUserID:_userID];

    self.title = profiles.name;

    [_headerView reloadDataWithProfiles:profiles];

    self.tableView.tableHeaderView = _headerView;
}

- (void)updateNavigationBar {

    if([_userID isEqualToString:DGCurrentAccount.userID]) {

        PPUnreadMessageSummaryObject *summary = [[PPUnreadMessageManager sharedInstance] summaryForType:PPUnreadMessageSummaryTypeMyNotify];

        UIImage *icon = [UIImage imageNamed:@"but-message"];

        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        [button setImage:icon forState:UIControlStateNormal];
        [button sizeToFit];
        button.imageView.layer.cornerRadius = button.imageView.width/2;
        button.imageView.layer.masksToBounds = YES;

        if(summary != nil && summary.count.integerValue > 0) {
            if ([summary.iconURLString length]) {
                [button sd_setImageWithURL:[NSURL URLWithString:summary.iconURLString] forState:UIControlStateNormal placeholderImage:nil options:SDWebImageRetryFailed];
            }
            else
            {
                 [button setImage:[UIImage imageNamed:@"icon-person-70"] forState:UIControlStateNormal];
            }

        }

        UIBarButtonItem *moreItem = [[UIBarButtonItem alloc] initWithCustomView:button];

        UIBarButtonItem *negItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        negItem.width = -10;

        self.navigationItem.rightBarButtonItems = @[negItem, moreItem];

        __weak typeof(self)weakSelf = self;
        [button setActionBlock:^(UIControl *control) {
            [MobClick event:@"68"];
            [weakSelf moreItemDidPressed:moreItem];
        } forControlEvents:UIControlEventTouchUpInside];
    } else {
        UIImage *icon = nil;

        if(_layoutType == PPProfileViewAlbumLayoutTypeTimeline) {
            icon = [UIImage imageNamed:@"icon-nav-grid-yellow"];
        } else {
            icon = [UIImage imageNamed:@"icon-nav-waterfull-yellow"];
        }

        UIBarButtonItem *layoutItem = [[UIBarButtonItem alloc] initWithImage:[icon imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(layoutItemDidPressed:)];
        self.navigationItem.rightBarButtonItem = layoutItem;
    }
}

- (void)changeLayoutType {
    if(_layoutType == PPProfileViewAlbumLayoutTypeFlow) {
        _layoutType = PPProfileViewAlbumLayoutTypeTimeline;
    } else {
        _layoutType = PPProfileViewAlbumLayoutTypeFlow;
    }

    [self.tableView reloadData];
}

- (void)layoutItemDidPressed:(UIBarButtonItem *)item {
    [MobClick event:@"85"];
    [self changeLayoutType];

    [self updateNavigationBar];
}

- (void)moreItemDidPressed:(UIBarButtonItem *)item {
    PPMessageTimelineViewController *messageViewConroller = [[PPMessageTimelineViewController alloc] init];
    messageViewConroller.summaryType = PPUnreadMessageSummaryTypeMyNotify;
    [self.navigationController pushViewController:messageViewConroller animated:YES];
}

- (void)fetchUserPublicInfoWithCallback:(void (^)(void))callback {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchPublicInfoWithTargetUserID:_userID callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [hud hide:YES];

        [strongSelf reloadDatasWithParameters:data error:error];
    }];
}

- (void)reloadDatasWithParameters:(NSDictionary *)parameters error:(NSError *)error {

    if(error == nil) {
        PPAccountProfiles *profiles = [PPAccountProfiles existingProfilesForUserID:_userID];
        [profiles mergeParameters:parameters];
        [profiles.managedObjectContext saveContext];

        [self reloadHeaderView];

    } else {
        [self.navigationController.view toastMessage:error.networkPrompt];
    }
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(_layoutType == PPProfileViewAlbumLayoutTypeFlow) {
        return CGFLOAT_MIN;
    } else {
        PPAlbumObject *album = [self.items safeObjectAtIndex:section];

        return [PPProfileTableViewSectionHeaderView heightForAlbum:album];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if(_layoutType == PPProfileViewAlbumLayoutTypeFlow) {
        return CGFLOAT_MIN;
    } else {
        PPAlbumObject *album = [self.items safeObjectAtIndex:section];

        if(album.commentCount > 3) {
            return 45;
        } else if(album.commentCount == 0) {
            return 15;
        } else {
            return 22;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(_layoutType == PPProfileViewAlbumLayoutTypeFlow) {
        return [tableView fd_heightForCellWithIdentifier:@"flowCell" cacheByIndexPath:indexPath configuration:^(id cell) {

        }];
    } else {
        PPAlbumObject *album = [self.items safeObjectAtIndex:indexPath.section];

        PPTimelineCommentObject *comment = [album.comments safeObjectAtIndex:indexPath.row];

        return [PPProfileTableViewCommentCell heightForComment:comment constrainedSize:CGSizeMake(tableView.width, 1000)];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(_layoutType == PPProfileViewAlbumLayoutTypeFlow) {
        return ceil(self.items.count/3.0);
    } else {
        return self.items.count;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(_layoutType == PPProfileViewAlbumLayoutTypeFlow) {
        return 1;
    } else {
        PPAlbumObject *album = [self.items safeObjectAtIndex:section];

        return MIN(album.comments.count, 3);
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if(_layoutType == PPProfileViewAlbumLayoutTypeFlow) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"flowCell" forIndexPath:indexPath];

        PPAlbumObject *leftAlbum = [self.items safeObjectAtIndex:(indexPath.section*3)];

        PPAlbumObject *middleAlbum = [self.items safeObjectAtIndex:(indexPath.section*3 + 1)];

        PPAlbumObject *rightAlbum = [self.items safeObjectAtIndex:(indexPath.section*3 + 2)];

        ((PPProfileTableViewFlowCell *)cell).leftAlbum = leftAlbum;
        ((PPProfileTableViewFlowCell *)cell).middleAlbum = middleAlbum;
        ((PPProfileTableViewFlowCell *)cell).rightAlbum = rightAlbum;
        ((PPProfileTableViewFlowCell *)cell).delegate = self;

        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell" forIndexPath:indexPath];

        PPAlbumObject *album = [self.items safeObjectAtIndex:indexPath.section];

        PPTimelineCommentObject *comment = [album.comments safeObjectAtIndex:indexPath.row];
        ((PPProfileTableViewCommentCell *)cell).comment = comment;

        return cell;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if(_layoutType == PPProfileViewAlbumLayoutTypeFlow) {
        UIView *headerView = [[UIView alloc] init];
        headerView.backgroundColor = [UIColor clearColor];
        headerView.frame = CGRectMake(0, 0, tableView.width, [self tableView:tableView heightForHeaderInSection:section]);

        return headerView;
    } else {
        PPAlbumObject *album = [self.items safeObjectAtIndex:section];

        PPProfileTableViewSectionHeaderView *headerView = [[NSBundle mainBundle] loadNibNamed:@"PPProfileTableViewSectionHeaderView" owner:nil options:nil].firstObject;
        headerView.backgroundColor = [UIColor clearColor];
        headerView.frame = CGRectMake(0, 0, tableView.width, [self tableView:tableView heightForHeaderInSection:section]);
        headerView.album = album;
        headerView.delegateViewController = self;
        headerView.delegate = self;

        return headerView;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if(_layoutType == PPProfileViewAlbumLayoutTypeFlow) {
        UIView *headerView = [[UIView alloc] init];
        headerView.backgroundColor = [UIColor clearColor];
        headerView.frame = CGRectMake(0, 0, tableView.width, [self tableView:tableView heightForFooterInSection:section]);

        return headerView;
    } else {
        UIView *headerView = [[UIView alloc] init];
        headerView.backgroundColor = [UIColor clearColor];
        headerView.frame = CGRectMake(0, 0, tableView.width, [self tableView:tableView heightForFooterInSection:section]);

        UIView *view = [[UIView alloc] init];
        view.frame = CGRectMake(0, 0, headerView.width, headerView.height - 10);
        view.backgroundColor = [UIColor whiteColor];
        [view addBottomBorderWithColor:kLineColor andWidth:kLineWidth];

        PPAlbumObject *album = [self.items safeObjectAtIndex:section];

        if(album.commentCount > 3) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.titleLabel.font = [UIFont systemFontOfSize:15];
            [button setTitle:[NSString stringWithFormat:@"全部%li条评论", album.commentCount] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor colorWithRGBHex:0x999999] forState:UIControlStateNormal];
            button.contentEdgeInsets = UIEdgeInsetsMake(4, 15, 4, 15);
            [button sizeToFit];
            button.frame = CGRectMake(0, 0, button.width, button.height);
            [view addSubview:button];

            __weak typeof(self)weakSelf = self;
            [button setActionBlock:^(UIControl *control) {
                [MobClick event:@"87"];
                PPCommentTimelineViewController *commentViewController = [[PPCommentTimelineViewController alloc] init];
                commentViewController.albumID = album.albumID.integerValue;
                commentViewController.ownerID = album.userID;
                commentViewController.delegate = self;
                commentViewController.userInfo = @(section);
                [weakSelf.navigationController pushViewController:commentViewController animated:YES];
            } forControlEvents:UIControlEventTouchUpInside];
        }

        [headerView addSubview:view];

        return headerView;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(_layoutType == PPProfileViewAlbumLayoutTypeFlow) {
        return;
    }

    [MobClick event:@"86"];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    PPAlbumObject *album = [self.items safeObjectAtIndex:indexPath.section];

    PPTimelineCommentObject *comment = [album.comments safeObjectAtIndex:indexPath.row];

    PPCommentTimelineViewController *commentViewController = [[PPCommentTimelineViewController alloc] init];
    commentViewController.albumID = album.albumID.integerValue;
    commentViewController.ownerID = album.userID;
    commentViewController.comment = comment;
    commentViewController.delegate = self;
    commentViewController.userInfo = @(indexPath.section);
    [self.navigationController pushViewController:commentViewController animated:YES];
}

#pragma mark - Timeline

- (NSArray *)initialItems {
    NSString *cacheFilePath = [self cacheFilePath];

    NSData *data = [NSData dataWithContentsOfFile:cacheFilePath];

    if(data != nil) {
        NSArray *items = [NSKeyedUnarchiver unarchiveObjectWithData:data];

        for(PPAlbumObject *album in items) {

            [album.comments enumerateObjectsUsingBlock:^(PPTimelineCommentObject *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
                NSString *content = nil;

                if(obj.receiver == nil) {
                    content = [NSString stringWithFormat:@"\u200B%@: %@", obj.sender.name, obj.content];;
                } else {
                    content = [NSString stringWithFormat:@"\u200B%@ 回复 \u200C%@: %@", obj.sender.name, obj.receiver.name, obj.content];
                }

                DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:content];
                editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
                editor.defaultFont = [UIFont systemFontOfSize:15];

                {
                    DGCoreTextPatternSetting *senderSetting = [[DGCoreTextPatternSetting alloc] init];
                    senderSetting.predicate = @"\u200B[\\u4e00-\\u9fa5\\w\\-]+";
                    senderSetting.defaultFont = [UIFont systemFontOfSize:15];
                    senderSetting.highlightedFont = [UIFont systemFontOfSize:15];
                    senderSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                    senderSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                    __weak typeof(self)weakSelf = self;
                    senderSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                        [weakSelf didPressedCommentSender:obj];
                    };
                    [editor preprocessWithPatternSetting:senderSetting];
                }

                {
                    DGCoreTextPatternSetting *receiverSetting = [[DGCoreTextPatternSetting alloc] init];
                    receiverSetting.predicate = @"\u200C[\\u4e00-\\u9fa5\\w\\-]+";
                    receiverSetting.defaultFont = [UIFont systemFontOfSize:15];
                    receiverSetting.highlightedFont = [UIFont systemFontOfSize:15];
                    receiverSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                    receiverSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                    __weak typeof(self)weakSelf = self;
                    receiverSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                        [weakSelf didPressedCommentReceiver:obj];
                    };
                    [editor preprocessWithPatternSetting:receiverSetting];
                }

                [editor process];

                obj.editor = editor;
            }];
        }

        return items;
    } else {
        return nil;
    }
}

- (void)cacheItems:(NSArray *)items {
    NSString *cacheFilePath = [self cacheFilePath];

    [NSKeyedArchiver archiveRootObject:items toFile:cacheFilePath];
}

- (void)fetchNewItems {
    [super fetchNewItems];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchAlbumsWithOwnerUserID:_userID pageSize:kCount pageIndex:1 callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        if(error == nil) {
            __block NSError *error_ = nil;

            dispatch_group_t group = dispatch_group_create();

            NSArray *albums = [data validArray];

            NSMutableDictionary *result = [NSMutableDictionary dictionary];

            dispatch_apply(albums.count, dispatch_get_global_queue(0, 0), ^(size_t idx) {

                dispatch_group_enter(group);

                NSNumber *albumID = [albums[idx] validNumberForKey:@"albumid"];
                [PPNetworkService getAlbumDetailsByAlbumID:albumID callback:^(id data, NSError *error) {

                    if(error == nil) {
                        @synchronized (result) {
                            [result setSafeObject:data forKey:@(idx)];
                        }
                    } else {
                        error_ = error;
                    }

                    dispatch_group_leave(group);
                }];
            });

            dispatch_group_notify(group, dispatch_get_main_queue(), ^{

                NSMutableArray *reorderedResult = [NSMutableArray array];

                for(NSNumber *idx in [result.allKeys sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
                    return [obj1 compare:obj2];
                }]) {

                    [reorderedResult addSafeObject:[result objectForKey:idx]];
                }

                [self didReceiveNewResult:reorderedResult ? : error];
            });

        } else {
            [self didReceiveNewResult:error];
        }
    }];
}

- (void)fetchMoreItems {
    [super fetchMoreItems];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchAlbumsWithOwnerUserID:_userID pageSize:kCount pageIndex:self.items.count/kCount + 1 callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        if(error == nil) {
            __block NSError *error_ = nil;

            dispatch_group_t group = dispatch_group_create();

            NSArray *albums = [data validArray];

            NSMutableDictionary *result = [NSMutableDictionary dictionary];

            dispatch_apply(albums.count, dispatch_get_global_queue(0, 0), ^(size_t idx) {

                dispatch_group_enter(group);

                NSNumber *albumID = [albums[idx] validNumberForKey:@"albumid"];
                [PPNetworkService getAlbumDetailsByAlbumID:albumID callback:^(id data, NSError *error) {

                    if(error == nil) {
                        @synchronized (result) {
                            [result setSafeObject:data forKey:@(idx)];
                        }
                    } else {
                        error_ = error;
                    }

                    dispatch_group_leave(group);
                }];
            });

            dispatch_group_notify(group, dispatch_get_main_queue(), ^{

                NSMutableArray *reorderedResult = [NSMutableArray array];

                for(NSNumber *idx in [result.allKeys sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
                    return [obj1 compare:obj2];
                }]) {

                    [reorderedResult addSafeObject:[result objectForKey:idx]];
                }

                [self didReceiveMoreResult:reorderedResult ? : error];
            });

        } else {
            [self didReceiveMoreResult:error];
        }
    }];
}

- (NSArray *)didReceiveNewResult:(id)result {
    NSArray *items = [super didReceiveNewResult:result];

    if([items count] >= kCount) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}

- (NSArray *)didReceiveMoreResult:(id)result {
    NSArray *items = [super didReceiveMoreResult:result];

    if([items count] >= kCount) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}

- (NSArray *)itemsFromResult:(id)result {
    NSMutableArray *items = [NSMutableArray array];

    for(NSDictionary *parameters in result) {

        PPAlbumObject *album = [PPAlbumObject albumForParameters:parameters];

        [album.comments enumerateObjectsUsingBlock:^(PPTimelineCommentObject *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
            NSString *content = nil;

            if(obj.receiver == nil) {
                content = [NSString stringWithFormat:@"\u200B%@: %@", obj.sender.name, obj.content];;
            } else {
                content = [NSString stringWithFormat:@"\u200B%@ 回复 \u200C%@: %@", obj.sender.name, obj.receiver.name, obj.content];
            }

            DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:content];
            editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
            editor.defaultFont = [UIFont systemFontOfSize:15];

            {
                DGCoreTextPatternSetting *senderSetting = [[DGCoreTextPatternSetting alloc] init];
                senderSetting.predicate = @"\u200B[\\u4e00-\\u9fa5\\w\\-]+";
                senderSetting.defaultFont = [UIFont systemFontOfSize:15];
                senderSetting.highlightedFont = [UIFont systemFontOfSize:15];
                senderSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                senderSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                __weak typeof(self)weakSelf = self;
                senderSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                    [weakSelf didPressedCommentSender:obj];
                };
                [editor preprocessWithPatternSetting:senderSetting];
            }

            {
                DGCoreTextPatternSetting *receiverSetting = [[DGCoreTextPatternSetting alloc] init];
                receiverSetting.predicate = @"\u200C[\\u4e00-\\u9fa5\\w\\-]+";
                receiverSetting.defaultFont = [UIFont systemFontOfSize:15];
                receiverSetting.highlightedFont = [UIFont systemFontOfSize:15];
                receiverSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                receiverSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                __weak typeof(self)weakSelf = self;
                receiverSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                    [weakSelf didPressedCommentReceiver:obj];
                };
                [editor preprocessWithPatternSetting:receiverSetting];
            }

            [editor process];

            obj.editor = editor;
        }];

        [items addObject:album];

    }

    return items;
}

- (UITableViewStyle)preferredTableViewStyle {
    return UITableViewStyleGrouped;
}

#pragma mark - PPProfileTableViewFlowCellDelegate

- (void)flowCell:(PPProfileTableViewFlowCell *)flowCell didSelectAlbum:(PPAlbumObject *)album {
    if(album.pictures.count == 0) {
        [self.navigationController.view toastMessage:@"图册暂时还没有图片哦"];

        return;
    }

    PPTimelinePictureViewController *pictureViewController = [[PPTimelinePictureViewController alloc] init];
    pictureViewController.pictures = album.pictures;
    pictureViewController.ownerID = album.userID;
    pictureViewController.albumTitle = album.title;
    [self.navigationController pushViewController:pictureViewController animated:YES];
}

- (void)didPressedCommentSender:(PPTimelineCommentObject *)comment {
    PPProfileViewController *profileViewController = [[PPProfileViewController alloc] init];
    profileViewController.userID = comment.sender.userID;
    [self.navigationController pushViewController:profileViewController animated:YES];
}

- (void)didPressedCommentReceiver:(PPTimelineCommentObject *)comment {
    PPProfileViewController *profileViewController = [[PPProfileViewController alloc] init];
    profileViewController.userID = comment.receiver.userID;
    [self.navigationController pushViewController:profileViewController animated:YES];
}

#pragma mark - Share

- (void)didSelectShareAlbum:(PPAlbumObject *)album {

    __block NSError *error_ = nil;
    __block NSString *title = nil;
    __block NSString *subtitle = nil;
    __block NSString *url = nil;
    __block UIImage *image_ = nil;
    __block NSString *pickpic = nil;

    dispatch_group_t group = dispatch_group_create();

    __weak typeof(self)weakSelf = self;

    dispatch_group_enter(group);
    [PPNetworkService getShareInfoWithAlbumID:album.albumID callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        if(error == nil) {
            title = [data validStringForKey:@"title"];
            subtitle = [data validStringForKey:@"title2"];
            url = [data validStringForKey:@"url"];
            pickpic = [data validStringForKey:@"pickpic"];
        } else {
            error_ = error;
        }

        dispatch_group_leave(group);

    }];

    dispatch_group_enter(group);
    [album queryCoverImageWithCompletion:^(UIImage *image, NSError *error) {
        if(error == nil) {
            image_ = image;
        } else {
            error_ = error;
        }

        dispatch_group_leave(group);
    }];

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{

        [hud hide:YES];

        if(error_ != nil) {
            [self.navigationController.view toastMessage:error_.networkPrompt];
        } else {
            [self shareAlbum:album title:title subtitle:subtitle url:url image:image_ pickpic:pickpic];
        }
    });
}

- (void)shareAlbum:(PPAlbumObject *)album title:(NSString *)title subtitle:(NSString *)subtitle url:(NSString *)url image:(UIImage *)image pickpic:pickpic {

    UIView *actionView = nil;

    if([[PPSocializationManager sharedInstance] support:PPSocializationTypeWeixin] && [[PPSocializationManager sharedInstance] support:PPSocializationTypeQQ]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:4];
    } else if([[PPSocializationManager sharedInstance] support:PPSocializationTypeWeixin]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:5];
    } else if([[PPSocializationManager sharedInstance] support:PPSocializationTypeQQ]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:6];
    } else {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:7];
    }

    UIView *displayView = self.navigationController.view;

    PPAlbumShareView *shareView = [[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareView" owner:nil options:nil].firstObject;
    shareView.alpha = 0;
    shareView.frame = displayView.bounds;
    shareView.cover = image;
    shareView.avatarURLString = album.ownerAvatar;
    shareView.name = album.ownerName;
    shareView.account = pickpic;
    shareView.title = album.title;
    [displayView addSubview:shareView];

    shareView.titleLabel.hidden = YES;
    UIImage *thumbnail = [shareView.contentView snapshotImage];
    shareView.titleLabel.hidden = NO;
    image = [shareView.contentView snapshotImage];

    actionView.frame = CGRectMake(0, displayView.height - actionView.height, displayView.width, actionView.height);

    DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:displayView contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleNone];

    __weak typeof(popoverView)weakPopover = popoverView;

    if([actionView respondsToSelector:@selector(wechatButton)]) {
        UIButton *wechatButton = [actionView valueForKey:@"wechatButton"];
        [wechatButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{

                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image thumbnail:thumbnail type:PPSocializationShareTypeWeixinChat];

            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(circleButton)]) {
        UIButton *circleButton = [actionView valueForKey:@"circleButton"];
        [circleButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{

                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image thumbnail:thumbnail type:PPSocializationShareTypeWeixinCircle];

            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(weiboButton)]) {
        UIButton *weiboButton = [actionView valueForKey:@"weiboButton"];
        [weiboButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{

                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image thumbnail:thumbnail type:PPSocializationShareTypeWeibo];

            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(qqButton)]) {
        UIButton *qqButton = [actionView valueForKey:@"qqButton"];
        [qqButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{

                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image thumbnail:thumbnail type:PPSocializationShareTypeQQChat];

            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(cancelButton)]) {
        UIButton *cancelButton = [actionView valueForKey:@"cancelButton"];
        [cancelButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:nil];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    popoverView.willDisplayBlock = ^{

        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            shareView.alpha = 1;
        } completion:nil];

    };

    popoverView.willDismissBlock = ^{

        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            shareView.alpha = 0;
        } completion:^(BOOL finished) {
            [shareView removeFromSuperview];
        }];

    };

    [popoverView displayAnimated:YES completion:nil];
}

#pragma mark - PPProfileTableViewSectionHeaderViewDelegate

- (void)sectionHeaderView:(PPProfileTableViewSectionHeaderView *)sectionHeaderView didSelectShareAlbum:(PPAlbumObject *)album {
    [self didSelectShareAlbum:album];
}

- (void)sectionHeaderView:(PPProfileTableViewSectionHeaderView *)sectionHeaderView didSelectCommentListForAlbum:(PPAlbumObject *)album {
    NSInteger section = [self.items indexOfObject:album];

    PPCommentTimelineViewController *commentViewController = [[PPCommentTimelineViewController alloc] init];
    commentViewController.albumID = album.albumID.integerValue;
    commentViewController.ownerID = album.userID;
    commentViewController.delegate = self;
    commentViewController.userInfo = @(section);
    [self.navigationController pushViewController:commentViewController animated:YES];
}

- (NSString *)cacheFilePath {
    NSString *directory = [NSString stringWithFormat:@"%@_Profiles", _userID];
    NSString *path = [[[NSFileManager defaultManager] documentDirectory] stringByAppendingPathComponent:directory];

    return path;
}

- (UIView *)emptyPromptViewForError:(NSError *)error {
    if(error != nil) {
        UILabel *label = [[UILabel alloc] init];
        label.text = error.networkPrompt;
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRGBHex:0x999999];
        [label sizeToFit];

        return label;
    } else {
        DGAlignmentButton *button = [DGAlignmentButton buttonWithType:UIButtonTypeCustom];
        button.style = DGAlignmentButtonStyleImageTop;
        button.spacing = 10;
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.contentEdgeInsets = UIEdgeInsetsMake(20, 20, 20, 20);
        [button setImage:[UIImage imageNamed:@"logo-gred"] forState:UIControlStateNormal];
        [button setTitle:@"暂无内容" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRGBHex:0x999999] forState:UIControlStateNormal];
        [button sizeToFit];

        return button;
    }
}

- (CGPoint)preferredEmptyPromptViewCenter {
    return CGPointMake(self.tableView.width/2, _headerView.height + (self.tableView.height - _headerView.height)*0.336);
}

#pragma mark - PPCommentTimelineViewControllerDelegate

- (void)commentTimelineViewController:(PPCommentTimelineViewController *)commentTimelineViewController didInsertComment:(PPTimelineCommentObject *)comment {
    NSInteger section = [commentTimelineViewController.userInfo integerValue];

    PPAlbumObject *album = [self.items safeObjectAtIndex:section];

    NSMutableArray *comments = [NSMutableArray arrayWithArray:album.comments];

    if(comments.count == 3) {
        [comments removeLastObject];
    }

    NSString *content = nil;

    if(comment.receiver == nil) {
        content = [NSString stringWithFormat:@"\u200B%@: %@", comment.sender.name, comment.content];;
    } else {
        content = [NSString stringWithFormat:@"\u200B%@ 回复 \u200C%@: %@", comment.sender.name, comment.receiver.name, comment.content];
    }

    DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:content];
    editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
    editor.defaultFont = [UIFont systemFontOfSize:15];

    {
        DGCoreTextPatternSetting *senderSetting = [[DGCoreTextPatternSetting alloc] init];
        senderSetting.predicate = @"\u200B[\\u4e00-\\u9fa5\\w\\-]+";
        senderSetting.defaultFont = [UIFont systemFontOfSize:15];
        senderSetting.highlightedFont = [UIFont systemFontOfSize:15];
        senderSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
        senderSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

        __weak typeof(self)weakSelf = self;
        senderSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
            [weakSelf didPressedCommentSender:comment];
        };
        [editor preprocessWithPatternSetting:senderSetting];
    }

    {
        DGCoreTextPatternSetting *receiverSetting = [[DGCoreTextPatternSetting alloc] init];
        receiverSetting.predicate = @"\u200C[\\u4e00-\\u9fa5\\w\\-]+";
        receiverSetting.defaultFont = [UIFont systemFontOfSize:15];
        receiverSetting.highlightedFont = [UIFont systemFontOfSize:15];
        receiverSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
        receiverSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

        __weak typeof(self)weakSelf = self;
        receiverSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
            [weakSelf didPressedCommentReceiver:comment];
        };
        [editor preprocessWithPatternSetting:receiverSetting];
    }

    [editor process];

    comment.editor = editor;

    [comments insertObject:comment atIndex:0];

    album.comments = comments;

    album.commentCount++;

    [self.tableView reloadData];
}

- (void)commentTimelineViewController:(PPCommentTimelineViewController *)commentTimelineViewController didRemoveComment:(PPTimelineCommentObject *)comment {
    NSInteger section = [commentTimelineViewController.userInfo integerValue];

    PPAlbumObject *album = [self.items safeObjectAtIndex:section];

    PPTimelineCommentObject *removedComment = nil;

    NSMutableArray *comments = [NSMutableArray arrayWithArray:album.comments];

    for(PPTimelineCommentObject *comment_ in comments) {
        if([comment.commentID isEqual:comment_.commentID]) {
            removedComment = comment_;
            break;
        }
    }

    album.commentCount--;

    if(removedComment != nil) {
        [comments removeObject:removedComment];

        album.comments = comments;
    }

    [self.tableView reloadData];
}

@end
